package com.wendu.oa.api.security;

import com.wendu.oa.common.CurrentUser;
import com.wendu.oa.common.Result;
import com.wendu.oa.common.TokenUtils;
import com.wendu.oa.dto.LoginDto;
import com.wendu.oa.exception.BusinessException;
import com.wendu.oa.exception.SysException;
import com.wendu.oa.service.security.LoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("/security/login")
public class LoginController {

    @Autowired
    private LoginService loginService;

    @PostMapping("")
    public Result login(@RequestBody LoginDto loginDto){

        try{
            CurrentUser currentUser = loginService.checkLogin(loginDto);

            //现在CurrentUser放到哪里
            //request.getSession().setAttribute("xxx",currentUser);

            //创建一个令牌
            String token = TokenUtils.loginSign(currentUser,loginDto.getU_pwd());

            return Result.OK((Object)token);
        }catch(BusinessException e){
            return Result.err(Result.CODE_ERR_BUSINESS,e.getMessage());
        }catch (SysException e){
            log.error("系统错误！",e);
            return Result.err(Result.CODE_ERR_SYS, "系统升级中...");
        }catch (Exception e){
            log.error("系统错误！",e);
            return Result.err(Result.CODE_ERR_SYS, "系统升级中...");
        }
    }
}
